import type { ApiRes } from '@/types/data'
import { useUserInfo } from '@/store/user'
const BASEURL = import.meta.env.VITE_APP_BASEURL

const store=useUserInfo()
interface requestTpye {
  url: string
  method?: 'GET' | 'POST' | 'DELETE' | 'PUT'
  header?: any
  data?: object
}
//'GET'| 'get'| 'post'| 'POST'| 'push'| 'PULL'| 'delete'| 'DELETE'

export const request = <T>({
  url,
  method = 'GET',
  header = {},
  data = {}
}: requestTpye): Promise<ApiRes<T>> => {
  const token = store.token
  if (token) {
    header.token=token
  }
  return new Promise((resolve, reject) => {
    uni.request({
      url: `${BASEURL}${url}`,
      method,
      header,
      data,
      success: res => {
        if (res.statusCode === 401) {
          //清空token
          store.setUserInfo('')

          uni.reLaunch({
            url:'/subcontract/login/index'
          })
          return
        }
        // 返回给页面的是响应体的数据
        resolve(res.data as ApiRes<T>)
      },
      fail: error => {
        reject(error)
      }
    })
  })
}
